package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/uuid"
	"house_srv/house"
	"house_srv/internal/svc"
	"house_srv/models/mysql"
	"house_srv/pkg"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderHouseLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderHouseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderHouseLogic {
	return &OrderHouseLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderHouseLogic) OrderHouse(in *house.OrderHouseRequest) (*house.OrderHouseResponse, error) {
	// todo: add your logic here and delete this line
	h := mysql.House{}
	err := h.HouseInfo()
	if err != nil {
		logx.Error("创建房源信息不存在")
		return nil, errors.New("创建房源信息不存在")
	}
	err = h.Create()
	if err != nil {
		logx.Error("创建房源信息错误")
		return nil, errors.New("创建房源信息错误")
	}
	orderSn := uuid.NewString()
	amount := h.HousePrice * 1
	order := mysql.Order{
		UserId:  in.UserId,
		OrderSn: orderSn,
		PayType: 1,
		Amount:  amount,
	}
	err = order.Create()
	if err != nil {
		logx.Error("创建订单信息错误")
		return nil, errors.New("创建订单信息错误")
	}
	houseOrder := mysql.HouseOrder{
		OrderId:       int64(order.ID),
		HouseId:       in.HouseId,
		HouseCity:     h.HouseCity,
		Address:       h.Address,
		HouseBuild:    h.HouseBuild,
		HouseFloor:    h.HouseFloor,
		HouseArea:     h.HouseArea,
		HouseDescribe: h.HouseDescribe,
		HouseCover:    h.HouseCover,
	}
	err = houseOrder.Create()
	if err != nil {
		logx.Error("创建房源订单信息错误")
		return nil, errors.New("创建房源订单信息错误")
	}
	//totalAmount := strconv.FormatFloat(2832, '2', 'f', 64)
	totalAmount := fmt.Sprintf("%.2f", amount)

	alipay := pkg.ALiPay{
		Subject:     "阿康支付",
		OutTradeNo:  orderSn,
		TotalAmount: totalAmount,
	}
	url := alipay.Pay()
	return &house.OrderHouseResponse{
		UrlPay:  url,
		OrderId: int64(order.ID),
	}, nil
}
